<script setup>
import { ref, onMounted } from 'vue';
import { getList,BuyOrder,BuyOrder2} from '@/api/zonghe';
import { ElMessage } from 'element-plus';


// 表格数据
const tableData = ref([]);
const total = ref(0); // 总条数
const page = ref(1); // 当前页码
const size = ref(8); // 每页条数
const proName = ref(''); // 查询名称

// 存储选中的数据
const purchaseOrder = ref([]);

// 获取数据
const getorder = async () => {
  try {
    const res = await getList({
      proName: proName.value,
      page: page.value,
      size: size.value
    });
    console.log(res);
    
    if (res.data.code === "200") {
      tableData.value = res.data.data.rows;
      total.value = res.data.data.total; 
    } else {
      ElMessage.warning(res.data.msg || '请求失败');
    }
  } catch (err) {
    ElMessage.error('请求失败: ' + err.message);
  }
};

// 监听多选框选中状态变化
const handleSelectionChange = (selection) => {
  purchaseOrder.value = selection; // 更新选中的数据
};
//购买方法
const buy = async (id) => {
  try {
    const hasPending = purchaseOrder.value.some(item => item.allocation === '请求中'||item.allocation === '已拒绝');
  if (hasPending) {
    ElMessage.warning('存在未处理的数据，无法购买');
    return;
  }
    // 添加确认对话框
    await ElMessageBox.confirm('确定要执行购买操作吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    const res = await BuyOrder({id:id});
    if (res.data.code === "200") {
      ElMessage.success(res.data.msg || '购买成功');
      getorder();
    }
  } catch (err) {
    // 如果是取消操作，不显示错误
    if (err !== 'cancel') {
      ElMessage.error('请求失败:' + err.message);
    }
  }
};

// 修改后的一键购买方法
const Allbuy = async () => {
  if (purchaseOrder.value.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  const hasPending = purchaseOrder.value.some(item => item.allocation === '请求中'||item.allocation === '已拒绝');
  if (hasPending) {
    ElMessage.warning('存在未处理的数据，无法购买');
    return;
  }
  
  try {
    // 添加确认对话框并显示选中数量
    await ElMessageBox.confirm(
      `确认购买选中的${purchaseOrder.value.length}条数据吗？`,
      '批量操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    let ids = purchaseOrder.value.map(item => item.id).join(',');
    const res = await BuyOrder2({ids:ids});

    if (res.data.code === "200") {
      ElMessage.success(res.data.msg || '购买成功');
      getorder();
      purchaseOrder.value = [];
    }
  } catch (err) {
    // 如果是取消操作，不显示错误
    if (err !== 'cancel') {
      ElMessage.error('请求失败:' + err.message);
    }
  }
};


// 分页
const handleSizeChange = (val) => {
  size.value = val;
  getorder();
};

const handleCurrentChange = (val) => {
  page.value = val;
  getorder();
};

// 查询
const handleSearch = () => {
  page.value = 1; // 重置页码  
  getorder();
};
const handleSelectable = (row) => {
  // 返回true表示可选，false表示禁用
  return !(row.allocation === '已拒绝' || row.delivered === '已购买');
};

// 组件挂载时调用
onMounted(() => {
  getorder();
});


</script>

<template>
  <el-card  class="full-card">
    <!-- 查询和操作区域 -->
    <el-row :gutter="20" class="query-row">
      <el-col :span="6">
        <el-input placeholder="请输入查询名称" v-model="proName" class="full-width-input" suffix-icon="Search"/>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-col>
      <el-col :span="4">
        <el-button type="success" @click="Allbuy">一键购买</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      border
      stripe
      @selection-change="handleSelectionChange" 
    >
      <!-- 多选框 -->
      <el-table-column 
        type="selection" 
        width="55" 
        align="center"
      :selectable="handleSelectable"
      />
      <!-- ID -->
      <el-table-column prop="id" label="ID" width="60" align="center" />
      <!-- 商品名称 -->
      <el-table-column prop="proName" label="商品名称" width="120" align="center" />
  
      <!-- 采购原因 -->
      <el-table-column prop="rensona" label="采购原因" width="140" align="center" />
      <!-- 单价 -->
      <el-table-column prop="price" label="单价" width="100" align="center" />
      <!-- 数量 -->
      <el-table-column prop="quantity" label="数量" width="100" align="center" />
      <!-- 总金额 -->
      <el-table-column prop="total" label="总金额" width="100" align="center" />
      <!-- 拨款状态 -->
      <el-table-column prop="allocation" label="拨款状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.allocation === '已拒绝' 
          ? 'danger' 
          : scope.row.allocation === '请求中' 
            ? 'warning' 
            : 'success'">
            {{ scope.row.allocation }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 购买状态 -->
      <el-table-column prop="delivered" label="购买状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.delivered === '未购买' ? 'danger' : 'success'">
            {{ scope.row.delivered }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 创建时间 -->
       
      <el-table-column prop="createTime" label="创建时间" width="160" align="center" />
      <!-- 更新时间 -->
      <el-table-column prop="updateTime" label="更新时间" width="160" align="center" />
      <!-- 操作列 -->
      <el-table-column label="操作" width="140" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="buy(scope.row.id)" v-if="scope.row.delivered === '未购买' && scope.row.allocation !== '已拒绝'">购买</el-button>
          <el-button type="info" size="small"   v-else-if="scope.row.delivered === '已购买'" disabled>已购买</el-button>
          <el-button type="danger" size="small" v-else disabled>{{ scope.row.delivered === '已拒绝' ? '已拒绝' : '无法操作' }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
  <!-- 修正后的分页组件 -->
    <el-pagination
       class="pagination"
       v-model:current-page="page"
       v-model:page-size="size"
       :total="total"
       :page-sizes="[8, 10, 12, 14]"
       layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    </el-card>
</template>

<style scoped>
/* 卡片样式 */
.full-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  /* 消除默认内边距 */
  :deep(.el-card__body) {
    padding: 20px;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.query-row {
  margin-bottom: 20px;
}

.table-container {
  flex: 1;
  min-height: 0; /* 修复flex布局滚动问题 */
}

.full-width-input {
  width: 100%;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

/* 表格样式优化 */
.el-table {
  flex: 1;
  
  /* 自动列宽 */
  :deep(th.el-table__cell),
  :deep(td.el-table__cell) {
    .cell {
      white-space: nowrap;
    }
  }
}

/* 按钮组间距调整 */
.el-col {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>